package com.itheima.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.itheima.article.dto.ArticleHomeDto;
import com.itheima.article.dto.ArticleInfoDto;
import com.itheima.article.mapper.ApArticleConfigMapper;
import com.itheima.article.mapper.ApArticleContentMapper;
import com.itheima.article.pojo.ApArticle;
import com.itheima.article.mapper.ApArticleMapper;
import com.itheima.article.pojo.ApArticleConfig;
import com.itheima.article.pojo.ApArticleContent;
import com.itheima.article.service.ApArticleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.article.vo.ArticleInfoVo;
import com.itheima.common.constants.BusinessConstants;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.vo.PageResultVo;
import com.itheima.common.vo.ResultVo;
import com.itheima.wemedia.feign.WmNewsFeign;
import com.itheima.wemedia.pojo.WmNews;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @version 1.0
 * @description <p>已发布的文章信息 业务实现</p>
 * @package com.itheima.article.service.impl
 */
@Service
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;

    @Autowired
    private WmNewsFeign wmNewsFeign;

    /**
     * 自媒体同步文章时，由admin远程调用保存文章信息
     *
     * @param dto
     */
    @Override
    @Transactional
    public void saveArticleInfo(ArticleInfoDto dto) {
        //1. 保存文章信息
        ApArticle apArticle = dto.getApArticle();
        // 还没有添加到数据库，id就有值，说明这个Id是旧文章的id,

        Long oldArticleId = apArticle.getId();
        if (null != oldArticleId) {
            // 旧文章要标记为删除
            deleteOldArticle(oldArticleId);
            apArticle.setId(null);// 重新生成新的id
        }
        save(apArticle); // 保存为新的文章
        log.info("保存文章信息成功:{}", dto.getWmNewsId());
        //2. 获取新增文章的id
        Long articleId = apArticle.getId();
        //3. 保存文章内容

        ApArticleContent apArticleContent = dto.getApArticleContent();
        apArticleContent.setId(articleId);// 主键即是文章id
        apArticleContent.setArticleId(articleId);
        if (articleId==null){
            apArticleContent.setId( System.currentTimeMillis());// 主键即是文章id
        }
        apArticleContentMapper.insert(apArticleContent);
        log.info("保存文章内容成功:{}", dto.getWmNewsId());
        //4. 保存文章配置
        ApArticleConfig apArticleConfig = dto.getApArticleConfig();
            apArticleConfig.setId(articleId);
            apArticleConfig.setArticleId(articleId);
        if (articleId==null){
            apArticleConfig.setId(System.currentTimeMillis());
        }
        apArticleConfigMapper.insert(apArticleConfig);
        log.info("保存文章配置成功:{}", dto.getWmNewsId());
        //5. 远程调用自媒体更新文章状态
        WmNews updatePojo = new WmNews();
        updatePojo.setId(dto.getWmNewsId()); // wm_news.id
        updatePojo.setStatus(BusinessConstants.WmNewsConstants.STATUS_PUBLISHED);
        updatePojo.setArticleId(articleId);
        ResultVo resultVo = wmNewsFeign.updateWmNews(updatePojo);
        if (resultVo.isSuccess()) {
            log.info("更新自媒体文章状态成功:{}", dto.getWmNewsId());
        } else {
            log.error("更新自媒体文章状态失败:{}", dto.getWmNewsId());
            throw new LeadNewsException("更新自媒体文章状态失败：" + resultVo.getErrorMessage());
        }
    }


    /**
     * 标记旧文章为删除状态
     *
     * @param oldArticleId
     */
    private void deleteOldArticle(Long oldArticleId) {
        ApArticleConfig updatePojo = new ApArticleConfig();
        updatePojo.setId(oldArticleId);
        updatePojo.setIsDelete(1);//1：删除
        apArticleConfigMapper.updateById(updatePojo);
    }

    /**
     * app端 文章分页查询
     * @param dto
     * @param loadType
     * @return
     */
    @Override
    public PageResultVo<ApArticle> findPage(ArticleHomeDto dto, int loadType) {
        //1. 参数校验
        dto.checkSize();
        //2. 查询, 条件放mybatis映射文件中来做判断
        List<ApArticle> list = getBaseMapper().findPage(dto,loadType);
        //3. 构建分页结果返回
        return PageResultVo.pageResult(dto.getLoaddir(), dto.getSize(), 1000l, list);
    }

    /**
     * 加载文章详情
     *
     * @param paramMap
     * @return
     */
    @Override
    public ArticleInfoVo loadArticleInfo(Map<String, String> paramMap) {
        //1. 获取文章ID
        long articleId = Long.parseLong(paramMap.get("articleId"));
        //2. 查询文章配置信息
        LambdaQueryWrapper<ApArticleConfig> queryWrapper = Wrappers.<ApArticleConfig>lambdaQuery()
                .eq(ApArticleConfig::getArticleId,articleId)
                .eq(ApArticleConfig::getIsDelete, 0)
                .eq(ApArticleConfig::getIsDown, 0);
        ApArticleConfig articleConfig = apArticleConfigMapper.selectOne(queryWrapper);
        if(null == articleConfig){
            throw new LeadNewsException("文章已下架或已删除!");
        }
        //3. 查询文章内容
        LambdaQueryWrapper<ApArticleContent> contentQueryWrapper = Wrappers.<ApArticleContent>lambdaQuery()
                .eq(ApArticleContent::getArticleId, articleId);
        ApArticleContent articleContent = apArticleContentMapper.selectOne(contentQueryWrapper);
        //4. 组装vo
        ArticleInfoVo vo = new ArticleInfoVo();
        vo.setConfig(articleConfig);
        vo.setContent(articleContent);
        //5. 返回
        return vo;
    }


}
